package com.inhg.inhg_android.net.catchers;

import com.inhg.inhg_android.net.interfaces.LoadingIf;
import com.inhg.inhg_android.net.model.BaseModel;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * Created by ZengYan on 2017/7/28.
 * Email : 810989881@qq.com
 *
 * @decs :
 */

public class TransformCatcher<T extends BaseModel> implements ObservableTransformer<T, T> {

    private LoadingIf mLoadingImpl;


    public TransformCatcher(@NonNull LoadingIf loadingIf) {
        this.mLoadingImpl = loadingIf;
    }

    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> observable) {
        return observable

                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        mLoadingImpl.showLoading();
                    }
                })
                .doAfterNext(new Consumer<T>() {
                    @Override
                    public void accept(@NonNull T t) throws Exception {
                        mLoadingImpl.hiddenLoading();
                    }
                }).doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        mLoadingImpl.hiddenLoading();
                    }
                });
    }
}
